<template>
  <div class="live">
    <danmaku-item v-if="errMsg" type="info" :message="errMsg" />
    <live v-else-if="ready" v-bind="props" />
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, onBeforeUnmount, ref, onBeforeMount } from 'vue';
import { parseProps } from '../../utils/props';
import { setCors, autoGet } from '../../utils/request';
import { setFaceOption } from '../../utils/face';

import Live from "./../../components/Live.vue"
import DanmakuItem from '../../components/DanmakuItem.vue';
import { Buffer } from 'buffer';



export default defineComponent({
  components: { Live, DanmakuItem },
  setup() {
    window.Buffer = Buffer
    // const onHashChange = () => window.open(location.href);
    // window.addEventListener('hashchange', onHashChange);
    // onBeforeUnmount(() => window.removeEventListener('hashchange', onHashChange));
    const props = reactive(parseProps("#" + location.hash.split("?")[1]));
    // const props = reactive(parseProps(location.hash));
    const canCORS = props.cors === 'true';
    setCors(canCORS);
    setFaceOption({
      method: props.face,
      expireDay: props.faceExpireDay,
    });

    const ready = ref(false);
    const errMsg = ref('');

    if (props.anchor) {
      ready.value = true;
    } else {
      // 获取房间信息
      autoGet(`https://api.live.bilibili.com/room/v1/Room/room_init?id=${props.room}`)
        .then(({ code, msg, data: { room_id, uid } }) => {
          if (code === 0) {
            props.room = parseInt(room_id);
            props.anchor = parseInt(uid);
            ready.value = true;
          } else {
            errMsg.value = msg;
          }
        })
        .catch(() => {
          errMsg.value = '获取房间信息失败';
          if (canCORS) errMsg.value += '，请检查是否正确禁用了浏览器的 web security 以允许直接跨域';
        });
    }

    onBeforeMount(() => {
   
    })


    return { props, ready, errMsg };
  },
});
</script>

<style scoped lang="less">

.live {
  margin: 0;
  padding: 0;
  height: 100vh;
  width: 100vw;
  background-color: transparent;
  box-sizing: border-box;
  -webkit-app-region: drag;
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
